﻿using Avalonia.Data;
using Avalonia.Data.Converters;
using Avalonia.Media;
using System;
using System.Globalization;

namespace Avalonia.BiliBili.Libs.Extensions.Converter
{
    public sealed class HexColorConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            try
            {
                if (value is string sourceText)
                {
                    if (parameter.ToString() == "x2")
                        sourceText = System.Convert.ToInt32(sourceText).ToString("X2");
                    else
                        sourceText = sourceText.Replace("#", "");
                    var color = sourceText.Length switch
                    {
                        4 => Color.Parse($"#00{sourceText}"),
                        6 or 8 => Color.Parse($"#{sourceText}"),
                        _ => Colors.Gray,
                    };
                    return new SolidColorBrush(color);
                }
            }
            catch { }
            return new BindingNotification(new InvalidCastException(), BindingErrorType.Error);
        }
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}